<?php

namespace app\common\behavior;

use think\Config;
use think\Lang;
use think\Loader;
use app\common\model\Keywords;
use app\common\model\Consume;
use app\common\model\User;
use app\common\model\Account;

class Common
{

    public function appDispatch(&$dispatch)
    {
        $pathinfoArr = explode('/', request()->pathinfo());
        if (!Config::get('url_domain_deploy') && $pathinfoArr && in_array($pathinfoArr[0], ['index', 'api'])) {
            //如果是以index或api开始的URL则关闭路由检测
            \think\App::route(false);
        }
    }
	
	public function appBegin(&$dispatch)
    {
		if(isset($dispatch['module']))
		{
			$model = $dispatch['module'][1];
			if($model == 'index')
			{				
				$key_model = new Keywords();
				$map = array('consumedays'=>['>', 0], 'price'=>['>', 0], 'consumetime'=>['<', strtotime(date('Y-m-d'))], 'delete_time'=>null);
				$keywords = $key_model->where($map)->select();
				foreach($keywords as $vo)
				{
					while($vo['consumetime']<strtotime(date('Y-m-d')) && $vo['consumedays']>0)
					{
						$next_consumetime = strtotime('+1 day', $vo['consumetime']);
						$user = User::get(['id'=>$vo['u_id']]);
						$conspoint = $vo['price']*$user['keywordsprice'];
						if($user['score'] >= $conspoint)
						{
							$data = array(
								'u_id' => $vo['u_id'],
								'username' => $vo['username'],
								'url' => $vo['url'],
								'keyword' => $vo['keyword'],
								'chupai' => $vo['chupai'],
								'xinpai' => $vo['xinpai'],
								'conspoint' => $conspoint,
								'constime' => $next_consumetime
							);
							Consume::create($data);
							
							$params = array(
								'u_id' => $vo['u_id'],
								'username' => $vo['username'],
								'tradenumber' => date('Ymd', $next_consumetime).mt_rand(1000000,9999999),
								'money' => $vo['price'],
								'trade_before' => $user['score'],
								'trade_point' => $conspoint,
								'trade_after' => $user['score'] - $conspoint,
								'tradetime' => $next_consumetime,
								'remarks' => '系统扣除'.date('Y-m-d', $next_consumetime).'日的费用，网址：'.$vo['url'].',关键字：'.$vo['keyword'],
							);
							Account::create($params);
								
							$user['score'] = $params['trade_after'];
							$user->save();
							
							$vo['consumedays'] = $vo['consumedays'] - 1;
							$vo['consumetime'] = $next_consumetime;
							$vo->save();
						}
						else
						{
							break;
						}
					}
				}
			}
        }
    }

    public function moduleInit(&$request)
    {
        // 设置mbstring字符编码
        mb_internal_encoding("UTF-8");

        // 如果修改了index.php入口地址，则需要手动修改cdnurl的值
        $url = preg_replace("/\/(\w+)\.php$/i", '', $request->root());
        // 如果未设置__CDN__则自动匹配得出
        if (!Config::get('view_replace_str.__CDN__')) {
            Config::set('view_replace_str.__CDN__', $url);
        }
        // 如果未设置__PUBLIC__则自动匹配得出
        if (!Config::get('view_replace_str.__PUBLIC__')) {
            Config::set('view_replace_str.__PUBLIC__', $url . '/');
        }
        // 如果未设置__ROOT__则自动匹配得出
        if (!Config::get('view_replace_str.__ROOT__')) {
            Config::set('view_replace_str.__ROOT__', preg_replace("/\/public\/$/", '', $url . '/'));
        }
        // 如果未设置cdnurl则自动匹配得出
        if (!Config::get('site.cdnurl')) {
            Config::set('site.cdnurl', $url);
        }
        // 如果未设置cdnurl则自动匹配得出
        if (!Config::get('upload.cdnurl')) {
            Config::set('upload.cdnurl', $url);
        }
        if (Config::get('app_debug')) {
            // 如果是调试模式将version置为当前的时间戳可避免缓存
            Config::set('site.version', time());
            // 如果是开发模式那么将异常模板修改成官方的
            Config::set('exception_tmpl', THINK_PATH . 'tpl' . DS . 'think_exception.tpl');
        }
        // 如果是trace模式且Ajax的情况下关闭trace
        if (Config::get('app_trace') && $request->isAjax()) {
            Config::set('app_trace', false);
        }
        // 切换多语言
        if (Config::get('lang_switch_on') && $request->get('lang')) {
            \think\Cookie::set('think_var', $request->get('lang'));
        }
        // Form别名
        if (!class_exists('Form')) {
            class_alias('fast\\Form', 'Form');
        }
    }

    public function addonBegin(&$request)
    {
        // 加载插件语言包
        Lang::load([
            APP_PATH . 'common' . DS . 'lang' . DS . $request->langset() . DS . 'addon' . EXT,
        ]);
        $this->moduleInit($request);
    }
}
